import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '../utils/auth'

interface UserState {
  token: string | null
  userInfo: {
    username: string
    role: string
  }
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: getToken(),
    userInfo: {
      username: '',
      role: ''
    }
  }),

  actions: {
    setToken(token: string) {
      this.token = token
      setToken(token)
    },

    setUserInfo(userInfo: { username: string; role: string }) {
      this.userInfo = userInfo
    },

    clearUserState() {
      this.token = null
      this.userInfo = {
        username: '',
        role: ''
      }
      removeToken()
    },

    // 登录成功后调用
    loginSuccess({ token, userInfo }: { token: string; userInfo: { username: string; role: string } }) {
      this.setToken(token)
      this.setUserInfo(userInfo)
    },

    // 退出登录
    logout() {
      this.clearUserState()
    }
  }
})